package com.sgy.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;

public class UpdateNote {

    /*
     * 创建会话
     * */
    public static void main(String[] args) throws Exception {
        RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 3);

        // 使用fluent编程风格
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("192.168.201.129:2181")
                .sessionTimeoutMs(50000)
                .connectionTimeoutMs(30000)
                .retryPolicy(exponentialBackoffRetry)
                .namespace("base")  // 独立的命名空间，对zookeeper上节点的命名都是/base
                .build();
        client.start();
        System.out.println("会话2被建立...");

        String path = "/curator/c1";
        // 获取数据内容
        byte[] bytes = client.getData().forPath(path);
        System.out.println("获取到的节点数据内容：" + new String(bytes));

        // 状态信息
        Stat stat = new Stat();
        client.getData().storingStatIn(stat).forPath(path);
        System.out.println("获取到的节点状态信息：" + stat);

        // 更新节点内容
        int version = client.setData().withVersion(stat.getVersion()).forPath(path, "修改内容".getBytes()).getVersion();
        System.out.println("当前最新版本：" + version);
        byte[] bytes1 = client.getData().forPath(path);
        System.out.println("修改后的数据内容：" + new String(bytes1));

        // BadVersionException
        client.setData().withVersion(stat.getVersion()).forPath(path, "修改内容2".getBytes());
    }
}
